package com.heima.wemedia.service.impl;
import java.util.ArrayList;
import java.util.Date;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ContentDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAutoAuditService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Shizhicong
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;
    @Autowired
    private WmMaterialService wmMaterialService;
    @Autowired
    private WmNewsAutoAuditService wmNewsAutoAuditService;

    @Override
    public ResponseResult newsPage(WmNewsPageReqDto dto) {
        if (Objects.isNull(dto)){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = WmThreadLocalUtil.getWmUserId();
        if (Objects.isNull(userId)){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        dto.checkParam();
        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        lambdaQuery().eq(WmNews::getUserId,userId)
                .eq(Objects.nonNull(dto.getStatus()),WmNews::getStatus,dto.getStatus())
                .eq(Objects.nonNull(dto.getChannelId()),WmNews::getChannelId,dto.getChannelId())
                .between(Objects.nonNull(dto.getBeginPubDate())&&Objects.nonNull(dto.getEndPubDate()),
                        WmNews::getPublishTime,
                        dto.getBeginPubDate(),dto.getEndPubDate())
                .like(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword())
                .orderByDesc(WmNews::getCreatedTime)
                .page(page);
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 提交文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        if (Objects.isNull(dto)||StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<String> contentImages =takeUrlInfoList(dto.getContent());
        WmNews wmNews = createNews(dto, contentImages);
        //保存或者更新文章
        if (ObjectUtil.isNull(dto.getId())){
            save(wmNews);
        }else {
            //删除文章图片与素材的关系
            wmNewsMaterialService.remove(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId,dto.getId()));
            updateById(wmNews);
        }
        //是草稿
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿
        //保存文章内容与素材的关系
        saveNewsMaterial(wmNews.getId(), contentImages, WemediaConstants.WM_CONTENT_REFERENCE);
        //保存封面图片与素材的关系
        saveNewsMaterial(wmNews.getId(), dto.getImages(), WemediaConstants.WM_COVER_REFERENCE);
        //自动提交
        wmNewsAutoAuditService.autoAudit(wmNews.getId());
        //发布文章到小程序
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //封面
    public WmNews createNews(WmNewsDto dto,List<String> contentImages) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        wmNews.setUserId(WmThreadLocalUtil.getWmUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        List<String> images = dto.getImages();
        if (!dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            log.warn(CollUtil.join(images,","));
            wmNews.setImages(CollUtil.join(images,","));
        }else {
            //无图文章
            if (contentImages.isEmpty()){
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                //多图文章
            }else if (contentImages.size()>=3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                //设置封面
                String many = CollUtil.join(contentImages.subList(0, 3), ",");
                wmNews.setImages(many);
            }else {
                //单图封面
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                wmNews.setImages(contentImages.get(0));
            }
        }
        return wmNews;
    }

    /**
     * 保存文章内容与素材的关系
     * @param newsId
     * @param images
     */
    public void saveNewsMaterial(Integer newsId, List<String> images, Short type) {
        if (CollectionUtils.isNotEmpty(images)){
            List<WmMaterial> wmMaterialList = wmMaterialService.getBaseMapper().selectList(
                    new LambdaQueryWrapper<WmMaterial>()
                            .in(WmMaterial::getUrl, images));
            List<Integer> materialIdList = wmMaterialList.stream().map(WmMaterial::getId).collect(Collectors.toList());
            for (int i = 0; i < materialIdList.size(); i++) {
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setMaterialId(materialIdList.get(i));
                wmNewsMaterial.setNewsId(newsId);
                wmNewsMaterial.setType(type);
                wmNewsMaterial.setOrd((short)i);
                wmNewsMaterialService.save(wmNewsMaterial);
            }
        }
    }

    /**
     * 获取文章中的图片信息
     * @param content
     * @return
     */
    public List<String> takeUrlInfoList(String content) {
        if (StringUtils.isBlank(content)){
            return new ArrayList<>();
        }
        List<ContentDto> contentDtoList = JSONUtil.toList(content, ContentDto.class);
        return contentDtoList.stream().filter(contentDto -> contentDto.getType().equals("image"))
                .map(ContentDto::getValue).collect(Collectors.toList());
    }

    /**
     * 文章查看
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        return ResponseResult.okResult(getById(id));
    }




}
